package com.itheima.service.impl;

import com.itheima.common.dto.OrderDto;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.OrderVo;
import com.itheima.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public Integer submitOrder(OrderDto orderDto) {

        //校验用户输入的验证码是否正确
        String validateCode = (String) redisTemplate.opsForValue().get(orderDto.getTelephone());
        if (!validateCode.equals(orderDto.getValidateCode())) {
            throw new RuntimeException("验证码错误");
        }

        //判断当前日期是否可以预约
        OrderSetting orderSetting = orderSettingMapper.findByOrderDate(orderDto.getOrderDate());

        if (orderSetting == null || orderSetting.getNumber() == 0) {
            throw new RuntimeException("当前日期没有设置可预约人数，无法预约");
        }

        //判断当前日期是否已经预约满
        if (orderSetting.getReservations() == orderSetting.getNumber()) {
            throw new RuntimeException("预约人数已满");
        }

        //如果该用户不是会员需要创建会员
        Member member = memberMapper.findByIdCard(orderDto.getIdCard());
        if (member == null) {
            member = new Member();
            member.setName(orderDto.getName());
            member.setSex(orderDto.getSex());
            member.setIdCard(orderDto.getIdCard());
            member.setPhoneNumber(orderDto.getTelephone());
            member.setRegTime(new Date());
            memberMapper.insert(member);
        }

        //查询当前用户是否已经预约当天的同一个套餐
        Integer num = orderMapper.findByMemberIdAndSetmealId(orderDto);
        if (num > 0) {
            throw new RuntimeException("当前用户当天已经预约过该套餐，不可再次预约");
        }

        //预约成功，更新预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingMapper.editReservationsByOrderDate(orderSetting);

        Order order = new Order();
        BeanUtils.copyProperties(orderDto, order);
        order.setOrderType("电话预约");
        order.setOrderStatus("未到诊");
        order.setMemberId(member.getId());
        orderMapper.insert(order);

        return order.getId();
    }

    @Override
    public OrderVo findById(Integer id) {
        return orderMapper.findOrderById(id);
    }
}
